package com.demo.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
	
	private static final String NAME="tf_db";  
	private static final int VERSION = 1;
	private Context context;
	private DatabaseHelper dbHelper;
	private SQLiteDatabase db;
	
	public DatabaseHelper(Context context) {   
		super(context, NAME, null, VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("create table user(" +
			"user_id integer primary key," +
			"username varchar(100)," +
			"user_icon blob," +
			"latitude double(10)," +
			"longitude double(10))"
		);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		db.execSQL("drop table if exits user");
		onCreate(db);
	}
	
	public DatabaseHelper open(){
		dbHelper = new DatabaseHelper(context);
		db = dbHelper.getReadableDatabase();
		return this;
	}
	
	public void update(ContentValues values){
		db = dbHelper.getWritableDatabase();
		db.update("user", values, "user_id="+values.getAsInteger("user_id"), null);
	}
	
	public Cursor execSql(String sql){
		dbHelper = new DatabaseHelper(context);
		db = dbHelper.getWritableDatabase();
		return db.rawQuery(sql,null);
	}
	
	public long insert(ContentValues values){
		db = dbHelper.getWritableDatabase();
		return db.insert("user", "user_id", values);
	}
	
	public Cursor getall(){
		return db.rawQuery("SELECT * FROM user", null);
	}
	
	public Boolean haveUserInfo(int userId){
		Boolean b=false;
		Cursor cursor=db.query("user", null,  "user_id="+userId, null, null, null,null);
		b=cursor.moveToFirst();
		cursor.close();
		return b;
	}
}

